package cn.client.ui.view.main.mindfulness

import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Star
import androidx.compose.material.icons.filled.StarOutline
import androidx.compose.material3.Icon
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import cn.client.R
import cn.client.data.remoteData.bean.InsertEvaluate
import cn.client.data.remoteData.bean.SelectUidAndMid
import cn.client.data.userStateManager
import cn.client.ui.components.BaseTopBar
import cn.client.ui.components.SubmitButton
import kotlinx.coroutines.launch

// 正念评分页面
@Composable
fun MindfulnessScoreScreen(
    mid: Int,
    navController: NavController,
    viewModel: MindfulnessViewModel = hiltViewModel()
){
    // 分数状态
    var myRating by remember { mutableIntStateOf(0) }
    // 文本内容
    var content: String by remember { mutableStateOf("") }

    val isEvaluateState = viewModel.isEvaluate.collectAsState(initial = false)
    val isEvaluate = isEvaluateState.value

    val userIdState = userStateManager.userId.collectAsState(initial = -1)
    val userId = userIdState.value
    val coroutineScope = rememberCoroutineScope()
    val context = LocalContext.current

    Log.d("MindfulnessScoreScreen","isEvaluate的值：$isEvaluate")

    // 尝试回显（发送获取当前正念评分的意图）
    val selectUidAndMid = SelectUidAndMid(mid = mid, uid = userId)
    viewModel.dispatch(MindfulnessViewModel.PageIntent.GetEvaluateInfo(selectUidAndMid))

    LaunchedEffect(Unit) {
        viewModel.pageEvents.collect {
            when(it) {
                is MindfulnessViewModel.PageEvent.Error -> {
                    Toast.makeText(context, "提示：${it.error}", Toast.LENGTH_LONG).show()
                }
                is MindfulnessViewModel.PageEvent.ResEvaluate -> {
                    if (it.evaluate!=null){
                        myRating = it.evaluate.score
                        content = it.evaluate.info.toString()
                    }
                }
                is MindfulnessViewModel.PageEvent.Success -> {
                    // 返回上一级
                    navController.navigateUp()
                }
                else -> {}
            }
        }
    }

    Scaffold(
        topBar = {
            BaseTopBar(
                title = "正念评分",
                onClickArrowBack = {
                    coroutineScope.launch {
                        // 返回上一级
                        navController.navigateUp()
                    }
                }
                )
        }
    ) { it ->
        Column(
            modifier = Modifier
                .padding(it)
                .fillMaxSize()
        ){
            /* 正念Item */

            /* 评分item */
            HomeSection(title = "评分") {
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(5.dp)
                ) {
                    // 显示打分条
                    RatingBar(
                        currentRating = myRating,
                        onRatingChanged = { myRating = it },
                        starsColor = Color.Blue
                    )
                    // 显示当前分数
                    Text(
                        text = "$myRating 分",
                        modifier = Modifier.padding(16.dp)
                    )
                }
            }
            /* 内容输入框 */
            Row(
                horizontalArrangement = Arrangement.Center,
                modifier = Modifier
                    .fillMaxWidth()
                    .wrapContentHeight()
                    .padding(5.dp)
            ) {
                TextField(
                    value = content,
                    onValueChange = { str -> content = str },
                    placeholder = { Text(stringResource(R.string.mindfulness_input_comment)) },
                    modifier = Modifier
                        .fillMaxWidth()
                        .wrapContentHeight()
                        .padding(5.dp)
                )
            }
            // 提交
            SubmitButton(
                onClickSubmitButton = {
                /* 发送评分意图 */
                    coroutineScope.launch {
                        val evaluate = InsertEvaluate(
                            mid = mid,
                            uid = userId,
                            score = myRating,
                            info = content
                        )
                        if (isEvaluate){
                            viewModel.dispatch(MindfulnessViewModel.PageIntent.UpdateEvaluate(evaluate))
                        } else {
                            viewModel.dispatch(MindfulnessViewModel.PageIntent.AddEvaluate(evaluate))
                        }
                    }
                }
            )
        }
    }
}



// 打分可组合项
@Composable
fun RatingBar(
    maxRating: Int = 5,
    currentRating: Int,
    onRatingChanged: (Int) -> Unit,
    starsColor: Color = Color.Yellow
){

    Row {
        for (i in 1..maxRating) {
            Icon(
                imageVector = if (i <= currentRating) Icons.Filled.Star
                else Icons.Filled.StarOutline,
                contentDescription = null,
                tint = if (i <= currentRating) starsColor
                else Color.Unspecified,
                modifier = Modifier
                    .clickable { onRatingChanged(i) }
                    .padding(4.dp)
            )
        }
    }
}

